package com.krui.iweibo.service.imageprocess;

import java.lang.Thread.State;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.krui.iweibo.app.IweiboApplication;

public class AsyncImageLoader {

	private static final int  MSG_ID = 1;
	public  static final String EXTRA_IMG_URL = "img_url";
	public  static final String EXTRA_IMG = "img";
	
	private ImageManager imageManager = new ImageManager(IweiboApplication.context);;
	
	/** 定义容量为50的队列*/
	private BlockingQueue<String> urlQueue = new ArrayBlockingQueue<String>(50);
	private Thread downLoadImageThread = new Thread(new DownLoadImageThread());
	private CallbackManager callbackManager = new CallbackManager();
	
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case MSG_ID:
				
				Bundle bundle = msg.getData();
				
				String url = bundle.getString(EXTRA_IMG_URL);
				Bitmap bitmap = bundle.getParcelable(EXTRA_IMG);
				
				callbackManager.callback(url, bitmap);
				break;

			default:
				break;
			}
		};
	};
	
	public Bitmap getImage(String url,ImageLoaderCallback callback){
		
		Bitmap bitmap = null;
		//缓存中读取图片
		if (imageManager.isHaveInCache(url)) {
			bitmap = imageManager.getFromCache(url);
			return bitmap;
		}
		//不存在就线程下载
		else {
			
			callbackManager.put(url, callback);
			startDownLoad(url);
		}
		
		return bitmap;
		
	}
	
	
	private void startDownLoad(String url){
		
		putUrlToUrlQueue(url);
		State state = downLoadImageThread.getState();
		if (state == State.NEW) {
			downLoadImageThread.start();
		}else if (state == State.TERMINATED) {
			downLoadImageThread = new Thread(new DownLoadImageThread());
			downLoadImageThread.start();
		}
	}
	
	
	
	private void putUrlToUrlQueue(String url){
		if (!urlQueue.contains(url)) {
			try {
				//阻塞方法，如果队列满将阻塞
				urlQueue.put(url);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private class DownLoadImageThread implements Runnable{

		private boolean isRun = true;
		@Override
		public void run() {
			
			try {
				while(isRun){
					String url = urlQueue.poll();
					if (url == null) break;
					Bitmap  bitmap = imageManager.safeGet(url);
					Message msg = handler.obtainMessage(MSG_ID);
					Bundle bundle = msg.getData();
					bundle.putString(EXTRA_IMG_URL, url);
					bundle.putParcelable(EXTRA_IMG, bitmap);
					
					handler.sendMessage(msg);
					
				}
			} catch (Exception e) {
				
			}finally{
				shutdown();
			}
		}
		
		
		/**
		 * 让外部也能关线程
		 */
		public void shutdown(){
			isRun = false;
		}
	}
}
